import {RecoilRoot, atom, useRecoilState, selector, useRecoilValue, useSetRecoilState} from 'recoil'
import React from 'react';
// 定义原子状态

const textState = atom({
  key: 'textState', // unique ID (with respect to other atoms/selectors)
  default: '1', // default value (aka initial value)
});

const charCountState = selector({
  key: 'charCountState', // unique ID (with respect to other atoms/selectors)
  get: ({get}) => {
    const text = get(textState);
    return text+'hh';
  },
});

const currentUserIDState = atom({
  key: 'CurrentUserID',
  default: 1,
});


const myDBQuery = (id)=>{
  return new Promise((resolve)=>{
    setTimeout(()=>{

      resolve('fbk'+id)
    }, 2000)
  })
}

const currentUserNameQuery = selector({
  key: 'CurrentUserName',
  get: async ({get}) => {
    const response = await myDBQuery(get(currentUserIDState));
    return response;
  },
});
function Child() {
  let [state, setText] = useRecoilState(textState)
  let val = useRecoilValue(charCountState) // 来读取值得

  return (
    <div>
      {state},{val}
      <button onClick={()=>setText('2')}>+</button>  
      <React.Suspense fallback={<div>加载中2。。。</div>}>
        <Child2/>
      </React.Suspense>
    </div>
  )
}

function Child2() {
  let name = useRecoilValue(currentUserNameQuery)
  let setId =  useSetRecoilState(currentUserIDState)
  return (
    <div>
      <div>name. {name}</div>
      <button onClick={()=>setId('2')}>+</button>  
    </div>
  )
}


function Demo() {
  return (
    <RecoilRoot>
      <React.Suspense fallback={<div>加载中。。。</div>}>
        <Child/>
      </React.Suspense>
    </RecoilRoot>
  )
}

export default Demo